package com.itmumu.miniwechat.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Component
public class JwtUtils {

    private static String secretKey = "ssjhfjs";


    /**
     * 生成token
     */
    public static String generateToken(Map<String, Object> map, Integer expDay) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, expDay);

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v.toString());
        });

        builder.withExpiresAt(instance.getTime());

        // 生成token
        return builder.sign(Algorithm.HMAC256(secretKey));
    }


    /**
     * 验证token
     */
    public static void verifyToken(String token) {
        JWT.require(Algorithm.HMAC256(secretKey)).build().verify(token);
    }



    /*
     * @description: 获取token组成信息
     * @author: wangm
     * @date: 2022/12/31 21:48
     * @param: [token]
     * @return: com.auth0.jwt.interfaces.DecodedJWT
     **/
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secretKey)).build().verify(token);
        return decodedJWT;
    }
}
